package 中等.模拟;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/spiral-matrix/
 */
public class 螺旋矩阵_54 {

    public static void main(String[] args) {

        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        spiralOrder(matrix);

    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        boolean left = false, right = true, up = false, down = false;
        int rows = matrix.length;
        int columns = matrix[0].length;
        int total = rows * columns;
        int row = 0, column = 0;
        while (list.size() < total) {
            if (right) {
                while (column < columns && matrix[row][column] != 101) {
                    list.add(matrix[row][column]);
                    matrix[row][column] = 101;
                    column++;
                }
                right = false;
                down = true;
                column--;
                row++;
            }
            if (down) {
                while (row < rows && matrix[row][column] != 101) {
                    list.add(matrix[row][column]);
                    matrix[row][column] = 101;
                    row++;
                }
                down = false;
                left = true;
                row--;
                column--;
            }
            if (left) {
                while (column >= 0 && matrix[row][column] != 101) {
                    list.add(matrix[row][column]);
                    matrix[row][column] = 101;
                    column--;
                }
                left = false;
                up = true;
                column++;
                row--;
            }

            if (up) {
                while (row >= 0 && matrix[row][column] != 101) {
                    list.add(matrix[row][column]);
                    matrix[row][column] = 101;
                    row--;
                }
                up = false;
                right = true;
                row++;
                column++;
            }
        }
        return list;
    }

}
